var protocol=require("../../netbus/protocol");
var netbus=require("../../netbus/netbus");
var Cmd=require("../Cmd");

var server={
	name:"broadcast",
	is_transfer:true,


	//用在非网关服务器上
	//接收到app_server发来的广播数据
	//服务号,命令号,0,协议类型,(用户数,[用户id数组]),(服务号,命令号,utag,协议类型,body的二进制流)
	on_recv_app_server_cmd:function(session,stype,ctype,utag,proto_type,body){

		if (stype!=Cmd.Stype.Broadcast && ctype!=Cmd.Request.BROADCAST){
			return;
		}

		var utag_array=[];
		var offset=10;
		var user_num=body.readUInt16BE(offset);
		offset+=2;
		for (var i=0;i<user_num;i++){
			var utag=body.readUInt32BE(offset);
			utag_array.push(utag);
			offset+=4;
		}

		var cmd_len=body.readUInt16BE(offset);
		offset+=2;
		var cmd=Buffer.allocUnsafe(cmd_len);
		body.copy(cmd,0,offset,offset+cmd_len);

		for(var j=0;j<user_num;j++){
			var utag=utag_array[j];
			//将app_server发来的数据转发给client
			var client_session=netbus.get_client_session(utag);
			if (!client_session){
				continue;
			}

			//不需要清空用户标识,因为utag在数据包中是0
			//cmd.writeUInt32BE(0,4);
			//直接发送到client
			client_session.send_cmd(cmd);
		}
	},

	//被动接收到客户端的断开连接
	on_disconnect:function(session,stype){
		
	}
}

module.exports = server;